import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/index.dart';
import 'package:yp/config/style.dart';
import 'package:yp/helper.dart';
import 'package:yp/router.dart';
import 'package:yp/services/api.dart';
import 'package:yp/utils/util.dart';
import 'package:yp/widgets/index.dart';

/// 领取优惠券
class CollectCoupons extends StatefulWidget {
  const CollectCoupons({Key key}) : super(key: key);

  @override
  _CollectCouponsState createState() => _CollectCouponsState();
}

class _CollectCouponsState extends State<CollectCoupons>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;
  bool _collect = false;
  dynamic coupon;
  String fromUserId = "", series = "";

  bool showTip = false;
  getinviterreward() {
    if (fromUserId.isEmpty) {
      toast("缺少推荐人");
      return;
    }
    // if (series.isEmpty) {
    //   toast("缺少优惠券信息");
    //   return;
    // }

    if (fromUserId.toString() ==
        SpUtil.getInt('empeNumId', defValue: 0).toString()) {
      toast('不可领取自的优惠券');
      Get.toNamed(RouteConfig.inviteFriend);
      return;
    }

    if (SpUtil.getInt('is_new_user', defValue: 1) != 1) {
      toast('不是新用户');
      //   Get.toNamed(RouteConfig.inviteFriend);

      return;
    }

    // return;
    var params = {
      "from_usr_num_id": fromUserId,
      'activity_id': 5,
      'mobile_phone': SpUtil.getString('number'),
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'new_member_flag': 1
    };
    print(params);
    // return;
    Api.inviterreward(params).listen((event) {
      if (event['code'] == 0) {
        // EasyLoading.show(status: "正在领取");

        Api.getCoupon2({
          "from_usr_num_id": fromUserId,
          'usr_num_id': SpUtil.getInt('empeNumId'),
          // 'coupon_num_id': series,
          "activity_id": 5, // 活动编号
          'mobile_phone': SpUtil.getString('number'),
          "access_token": SpUtil.getString('token'),
        }).listen((event) {
          EasyLoading.dismiss();
          if (event['code'] == 0) {
            Api.cardmeidacouponruleget({
              "series": series,
            }).listen((event) {
              if (event['code'] == 0) {
                toast("领取成功");
                setState(() {
                  _collect = true;
                  coupon = event;
                });
              } else {
                toast("优惠惠券信息获取失败");
              }
            });
          } else {
            Get.toNamed(RouteConfig.inviteFriend);
            toast(event['message']);
          }
        });
      } else {
        toast(event['message']);
      }
    });
  }

  @override
  void initState() {
    if (Get.arguments == null) {
      fromUserId = getQueryVariable('usr_num_id').toString();
      series = getQueryVariable('series').toString();
      setState(() {});

      if (SpUtil.getString('token').isEmpty) {
        // Get.offAllNamed(RouteConfig.mallLogin, arguments: {
        //   'from_usr_num_id': fromUserId,
        //   'seriesID': series,
        // });
        var url = Config.WEB_URL +
            'mall_login?from_usr_num_id=$fromUserId&seriesID=$series&page=collect_coupons';

        webpay(url);
      }
    } else {
      fromUserId = Get.arguments['usr_num_id'].toString();
      series = Get.arguments['series'].toString();
      setState(() {});

      if (SpUtil.getString('token').isEmpty) {
        // Get.offAllNamed(RouteConfig.mallLogin, arguments: {
        //   'from_usr_num_id': fromUserId,
        //   'seriesID': series,
        // });
        var url = Config.WEB_URL +
            'mall_login?from_usr_num_id=$fromUserId&seriesID=$series&page=collect_coupons';

        webpay(url);
      }
    }

    super.initState();
    // print(url);
    _controller = AnimationController(vsync: this);
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(
        BoxConstraints(
            maxWidth: MediaQuery.of(context).size.width,
            maxHeight: MediaQuery.of(context).size.height),
        designSize: Size(750, 1334),
        orientation: Orientation.portrait);
    return Stack(
      children: [
        Scaffold(
          appBar: YPNavigationBar(
            '领取优惠券',
            backgroundColor: Color(0xffea5504),
            backBtnColor: EsColors.White,
            titleColor: EsColors.White,
            onPressed: () {
              Get.offAllNamed(RouteConfig.main);
            },
            canBack: false,
          ),
          // floatingActionButton: GestureDetector(
          //   onTap: () {
          //     Get.offAllNamed(RouteConfig.main);
          //   },
          //   child: Container(
          //     width: 50,
          //     height: 50,
          //     decoration: BoxDecoration(
          //       color: Color(0xfff84034),
          //       borderRadius: BorderRadius.circular(25),
          //     ),
          //     child: Icon(Icons.home, color: Colors.white),
          //   ),
          // ),
          body: CustomScrollView(
            slivers: [
              SliverToBoxAdapter(
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    SizedBox(
                      child: Container(
                        margin: EdgeInsets.fromLTRB(24.w, 100.w, 24.w, 0),
                        padding: EdgeInsets.fromLTRB(60.w, 100.w, 60.w, 80.w),
                        decoration: BoxDecoration(
                            color: EsColors.White,
                            borderRadius:
                                BorderRadius.all(Radius.circular(10))),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            AnimatedContainer(
                              duration: Duration(milliseconds: 300),
                              width: _collect ? 640.w : 580.w,
                              height: _collect ? 200.w : 170.w,
                              child: AnimatedOpacity(
                                opacity: _collect ? 1 : 0,
                                duration: Duration(milliseconds: 300),
                                child: Row(children: [
                                  if (coupon != null)
                                    Expanded(
                                      flex: 1,
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.center,
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          RichText(
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              text: TextSpan(children: [
                                                TextSpan(
                                                    text: '￥',
                                                    style: TextStyle(
                                                        fontSize: EsSizes.LG,
                                                        fontWeight:
                                                            EsFontWeights
                                                                .SemiBold,
                                                        color: EsColors.White)),
                                                TextSpan(
                                                    text:
                                                        '${coupon['face_value'].toString().replaceAll(".0", "")}',
                                                    style: TextStyle(
                                                        fontSize: 40,
                                                        fontWeight:
                                                            EsFontWeights
                                                                .SemiBold,
                                                        color: EsColors.White))
                                              ])),
                                          Container(
                                            padding: EdgeInsets.symmetric(
                                                vertical: 0, horizontal: 10),
                                            decoration: BoxDecoration(
                                                color: Color(0xffd32f14),
                                                borderRadius:
                                                    BorderRadius.circular(8)),
                                            child: Text(
                                              coupon['least_cost'] == 0
                                                  ? '无门槛'
                                                  : '满${coupon['least_cost'].toString().replaceAll(".0", "")}元可用',
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              style: TextStyle(
                                                  color: EsColors.White,
                                                  fontSize: EsSizes.XS,
                                                  fontWeight:
                                                      EsFontWeights.Normal),
                                            ),
                                          )
                                        ],
                                      ),
                                    ),
                                  if (coupon != null)
                                    Expanded(
                                        flex: 2,
                                        child: Column(
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.center,
                                          children: [
                                            Text(
                                              '${coupon['title']}',
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              style: TextStyle(
                                                  color: EsColors.Money,
                                                  fontSize: EsSizes.MD,
                                                  fontWeight:
                                                      EsFontWeights.SemiBold),
                                            ),
                                            SizedBox(height: 14),
                                            if (coupon["fixed_term"] == null)
                                              Text(
                                                "${DateFormat('yyyy.MM.dd').format(DateTime.parse(coupon['use_begin_date']))}-${DateFormat('yyyy.MM.dd').format(DateTime.parse(coupon['use_begin_end']))}",
                                                style: TextStyle(
                                                    color: EsColors
                                                        .ContentSecondary,
                                                    fontSize: EsSizes.XS,
                                                    fontWeight:
                                                        EsFontWeights.Normal),
                                              ),
                                            if (coupon["fixed_term"] != null)
                                              Text(
                                                "自领券${coupon["fixed_term"]}日内",
                                                style: TextStyle(
                                                    color: EsColors
                                                        .ContentSecondary,
                                                    fontSize: EsSizes.XS,
                                                    fontWeight:
                                                        EsFontWeights.Normal),
                                              ),
                                            // Text(
                                            //   '2019.05.23-2019.05.23',
                                            //   style: TextStyle(
                                            //       color: EsColors.ContentSecondary,
                                            //       fontSize: EsSizes.XS,
                                            //       fontWeight: EsFontWeights.Normal),
                                            // ),
                                          ],
                                        ))
                                ]),
                              ),
                              decoration: BoxDecoration(
                                  image: DecorationImage(
                                      fit: BoxFit.fill,
                                      image: AssetImage(_collect
                                          ? 'assets/images/give_coupons_bg2.png'
                                          : 'assets/images/give_coupons.png'))),
                            ),
                            SizedBox(
                              height: 80.w,
                            ),
                            GestureDetector(
                              onTap: () {
                                if (_collect) {
                                  if (!kIsWeb) {
                                    Get.offAllNamed(RouteConfig.main);
                                    return;
                                  }
                                  // toast("请下载app使用");
                                  webpay("${Config.WEB_DOWN_URL}download.html");

                                  // /// 跳转到app失败 进入下载页或者提示系统浏览器打开
                                  // Future.delayed(Duration(seconds: 1), () {
                                  //   if (isWechat()) {
                                  //     // toast('请在系统浏览器打开本页面');
                                  //     setState(() {
                                  //       showTip = true;
                                  //     });
                                  //   } else {
                                  //     /// 进入下载页
                                  //     webpay(
                                  //         "${Config.WEB_DOWN_URL}download.html");
                                  //   }
                                  // });
                                  // webpay("yinpinhui://zrhsh.com/app");
                                } else {
                                  print('立即领取1');

                                  getinviterreward();

                                  setState(() {});
                                }
                              },
                              child: Container(
                                width: double.infinity,
                                decoration: BoxDecoration(
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(28)),
                                  gradient: LinearGradient(
                                    begin: Alignment.topCenter,
                                    end: Alignment.bottomCenter,
                                    colors: [
                                      Color(0xfffc7253),
                                      Color(0xfff84034)
                                    ],
                                  ),
                                ),
                                alignment: Alignment.center,
                                padding: EdgeInsets.symmetric(vertical: 20.w),
                                child: Text(
                                  _collect ? '立即使用' : '立即领取',
                                  style: TextStyle(
                                      color: EsColors.White,
                                      fontSize: EsSizes.LG * 2.sp,
                                      fontWeight: EsFontWeights.Medium),
                                ),
                              ),
                            ),
                            SizedBox(
                              height: 15.w,
                            ),
                            Text(
                              '请下载app使用',
                              style: TextStyle(
                                  color: EsColors.White,)
                            )
                          ],
                        ),
                      ),
                    ),
                    // Positioned(
                    //     top: 30.w,
                    //     child: SizedBox(
                    //       child: CachedImage(borderRadius: 50.w, width: 100.w, height: 100.w, path: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.zhimg.com%2F50%2Fv2-7acc94c1b8ca2c6cffa56207169a8ef6_hd.jpg&refer=http%3A%2F%2Fpic1.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1634143012&t=f666e2ace0246f733bfb03a2a5be8b71'),
                    //     )),
                    // Positioned(
                    //     top: 120.w,
                    //     child: Container(
                    //       padding: EdgeInsets.symmetric(vertical: 2.w, horizontal: 16.w),
                    //       decoration: BoxDecoration(
                    //         color: EsColors.White,
                    //         borderRadius: BorderRadius.all(Radius.circular(18.w)),
                    //         border: Border.all(color: EsColors.BackGround, width: 2.w),
                    //       ),
                    //       child: Text(
                    //         'Fanny',
                    //         style: TextStyle(color: EsColors.TitleSecondary, fontSize: EsSizes.XS * 2.sp, fontWeight: EsFontWeights.Medium),
                    //       ),
                    //     ))
                  ],
                ),
              ),
              // SliverToBoxAdapter(
              //     child: AnimatedOpacity(
              //   opacity: _collect ? 1 : 0,
              //   duration: Duration(milliseconds: 300),
              //   child: Padding(
              //     padding: EdgeInsets.symmetric(vertical: 32.w, horizontal: 40.w),
              //     child: Row(
              //       children: [
              //         Expanded(child: Container(color: EsColors.BackGround, height: 1.w)),
              //         Container(width: 8.w, height: 8.w, decoration: BoxDecoration(color: EsColors.White, borderRadius: BorderRadius.all(Radius.circular(8.w)))),
              //         SizedBox(width: 24.w),
              //         Text(
              //           '优惠券可用商品',
              //           overflow: TextOverflow.ellipsis,
              //           style: TextStyle(color: EsColors.White, fontSize: EsSizes.MD * 2.sp, fontWeight: EsFontWeights.Normal),
              //         ),
              //         SizedBox(width: 24.w),
              //         Container(
              //             width: 8.w,
              //             height: 8.w,
              //             decoration: BoxDecoration(
              //                 color: EsColors.White,
              //                 borderRadius: BorderRadius.all(Radius.circular(
              //                   8.w,
              //                 )))),
              //         Expanded(child: Container(color: EsColors.BackGround, height: 1.w))
              //       ],
              //     ),
              //   ),
              // )),
              // SliverPadding(
              //   padding: EdgeInsets.only(left: 20.w, right: 20.w, bottom: 30.w),
              //   sliver: SliverGrid(
              //       delegate: SliverChildBuilderDelegate((context, index) {
              //         return _goodsItem();
              //       }, childCount: _collect ? 30 : 0),
              //       gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(childAspectRatio: 0.68, crossAxisCount: 2, crossAxisSpacing: 10, mainAxisSpacing: 10)),
              // ),
            ],
          ),
          backgroundColor: Color(0xffea5504),
        ),
        // if (showTip)
        //   Container(
        //     color: Colors.black45.withOpacity(.75),
        //     child: Center(
        //         child: Text(
        //       "请点击右上角的'...'\n然后选择在浏览器打开",
        //       style: TextStyle(
        //         color: Colors.white,
        //         fontSize: 18,
        //       ),
        //       textAlign: TextAlign.center,
        //     )),
        //   ),
      ],
    );
  }

  /// 商品item
  Widget _goodsItem() {
    return Container(
      decoration: EsDecoration.BoxShadowWithRadius,
      padding: EdgeInsets.all(20.w),
      child: Column(
        children: [
          CachedImage(
              width: 300.w,
              height: 300.w,
              scale: BoxFit.cover,
              path:
                  'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F014e605543b14b0000019ae902dbd3.jpg%401280w_1l_2o_100sh.jpg&refer=http%3A%2F%2Fimg.zcool.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1634144288&t=876552505ee5d187fed1103b1619a7c0'),
          SizedBox(height: 10.w),
          Text('很好吃的巧克力夹心生日大蛋糕',
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                  color: EsColors.TitleSecondary,
                  fontSize: 2 * EsSizes.SM.sp,
                  fontWeight: EsFontWeights.Normal)),
          SizedBox(height: 10.w),
          Row(
            children: [
              Text('￥290',
                  style: TextStyle(
                      fontSize: EsSizes.LG * 2.sp,
                      color: EsColors.Primary,
                      fontWeight: EsFontWeights.Medium)),
              SizedBox(width: 8.w),
              Expanded(
                  child: Text('￥298',
                      style: TextStyle(
                          fontSize: EsSizes.XXS * 2.sp,
                          decoration: TextDecoration.lineThrough,
                          color: EsColors.ContentSecondary,
                          fontWeight: EsFontWeights.Normal))),
              GestureDetector(
                onTap: () {
                  print('加购物车');
                },
                child: Container(
                  // width: 48.w,
                  // height: 48.w,
                  alignment: Alignment.center,
                  padding: EdgeInsets.all(8.w),
                  decoration: BoxDecoration(
                      color: EsColors.Primary,
                      borderRadius: BorderRadius.all(Radius.circular(30.w)),
                      border: Border.all(color: EsColors.Primary)),
                  child: Icon(
                    Icons.shopping_cart,
                    color: EsColors.White,
                    size: 30.w,
                  ),
                ),
              )
            ],
          ),
        ],
      ),
    );
  }
}
